#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : micah
# @time    :  
# @function: 
# @version :


# import time
# import requests
#
#
# def main():
#     for i in range(30):
#         res = requests.get('https://www.baidu.com')
#         print(f'第{i + 1}次请求，status= {res.status_code}')
#
#
# if __name__ == '__main__':
#     start = time.time()
#     main()
#     print(f'同步发送30次请求，耗时：{time.time() - start}')
#

import asyncio
import time
import aiohttp


async def requests_data(client, i):
    res = await client.get('https://www.baidu.com')
    print(f'第{i + 1}次请求，status_code={res.status}')


async def main():
    # aiohttp.ClientSession()  # 类似于requests的session()
    async with aiohttp.ClientSession() as client:
        tasks = []
        for i in range(30):
            # 获取的是协程对象
            res = requests_data(client, i)
            # 创建成task 对象
            task = asyncio.create_task(res)
            await asyncio.sleep(0.2)
            tasks.append(task)
        await asyncio.wait(tasks)


if __name__ == '__main__':
    start = time.time()
    # 开始事件循环
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    end = time.time()
    print(f'异步发送30次请求，耗时：{end - start}')
